#version 130

uniform vec3 playerPos;
uniform vec3 sunPosition;
uniform float elapsedTime;
uniform sampler3D noiseTexture;

// Vertex shader input
in vec3 fWorldPos;
in vec3 fNormal;
in float fIntensity;

float tween(float t)
{
	return clamp(t*t*t*(t*(t*6-15)+10),0,1);
}

void main()
{
	vec3 normal = normalize(fNormal);
	vec3 up = normalize(fWorldPos);
	vec3 samplePos = fWorldPos;
	float ss = 0.195;
	float ns = 1.0;
	float timescale = 0.5;
	float s = 2;

	vec3 samp_yz = texture3D(noiseTexture, vec3(samplePos.yz * ss, elapsedTime*timescale)).rgb - vec3(0.5);
	vec3 samp_xz = texture3D(noiseTexture, vec3(samplePos.xz * ss, elapsedTime*timescale)).rgb - vec3(0.5);
	vec3 samp_xy = texture3D(noiseTexture, vec3(samplePos.xy * ss, elapsedTime*timescale)).rgb - vec3(0.5);
	
	vec3 norm_xy = samp_xy.r * vec3(1, 0, 0) + samp_xy.g * vec3(0, 1, 0) + samp_xy.b * vec3(0, 0, 1);
	vec3 norm_xz = samp_xz.r * vec3(0, 0, 1) + samp_xz.g * vec3(1, 0, 0) + samp_xz.b * vec3(0, 1, 0);
	vec3 norm_yz = samp_yz.r * vec3(0, 1, 0) + samp_yz.g * vec3(0, 0, 1) + samp_yz.b * vec3(1, 0, 0);	
	
	vec3 modNorm = norm_yz*normal.x + norm_xz*normal.y + norm_xy*normal.z;

	normal = normalize(mix(normal, modNorm, ns));
	
	//normal = normalize(normal);
	
	int c1 = 3;
	int c2 = 5;
	
	vec3 FtoP = normalize(playerPos - fWorldPos);
	vec3 FtoS = normalize(sunPosition - fWorldPos);
	vec3 sum = normalize(FtoP + FtoS);
	
	float alpha = 0.5;
	
	float reflect = 0.0;
	reflect = dot(sum, normal);
	reflect = max(0, (reflect - 0.94)/0.04);
	reflect = min(1, reflect*3);
	reflect *= fIntensity;
	
	float closeToNorm = clamp(dot(FtoP, normal)*1.5,0,1);
	//closeToNorm = tween(closeToNorm);
	//closeToNorm = tween(closeToNorm);
	//closeToNorm = tween(closeToNorm);
	//closeToNorm = tween(closeToNorm);
	vec3 hclr = mix(vec3(0.4, 0.7, 1.0), vec3(0.1, 0.1, 0.4), closeToNorm);
	alpha = mix(0.5, 0.3, closeToNorm);
	
	alpha = mix(alpha, 0.7, reflect);
	
	hclr = fIntensity*hclr;
	vec3 clr = mix( hclr,vec3(1,1,1), reflect);
	gl_FragColor = vec4( clr, alpha);  
}
